package com.hongdee.crm.exsurance.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.dao.IImpHibernateDao;
import com.hongdee.common.dao.IImpJdbcDao;
import com.hongdee.common.dao.IJdbcDao;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.Constant;
import com.hongdee.crm.carConfig.service.ITcrmCarConfService;
import com.hongdee.crm.exsurance.dao.ITCrmCarExsuranceDao;
import com.hongdee.crm.exsurance.entity.TCrmCarExsurance;
import com.hongdee.crm.exsurance.service.ITCrmCarExsuranceService;
import com.hongdee.crm.task.service.ICarBaseCountService;
import com.hongdee.crm.task.service.ITCrmCarWorkorderTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by My on 2017/2/17.
 */
@Service
public class TCrmCarExsuranceServiceImpl implements ITCrmCarExsuranceService {

    private String tabName = "T_CRM_CAR_EXSURANCE";
    private String entity = "TCrmCarExsurance";

    @Autowired
    private ITCrmCarExsuranceDao itCrmCarExsuranceDao;
    @Autowired
    private IImpHibernateDao iImpHibernateDao;
    @Autowired
    private IImpJdbcDao iImpJdbcDao;

    @Autowired
    private IJdbcDao jdbcDao;
    @Autowired
    private IHibernateDao iHibernateDao;
    @Autowired
    private ITcrmCarConfService confService;
    @Autowired
    private ITCrmCarWorkorderTaskService itCrmCarWorkorderTaskService;
    @Autowired
    private ICarBaseCountService iCarBaseCountService;


    /**
     * @param id 主键
     * @return Map
     * @throws Exception
     * @desc 延保明细
     * @author 徐钦勇
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择记录");
        }
        String sql = "select * from " + tabName + " where id = ? ";
        return this.itCrmCarExsuranceDao.info(sql, new Object[]{id});
    }

    /**
     * @param start 当前页面
     * @param limit 页面大小
     * @param data  查询条件集合
     * @return Map
     * @throws Exception
     * @desc 分页查询
     * @author 徐钦勇
     */
    @Override
    public Map page(String start, String limit, Map data, String uid) throws Exception {
        /****
         * 车辆关联延保记录，
         *
         * **/
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        String companyId = StringUtil.formatEmpty(data.get("companyId"));
        if ("".equals(companyId)) {
            companyId = TokenUtil.getCompanyId(uid);
        }
        String area = StringUtil.formatEmpty(data.get("area"));
        String brand = StringUtil.formatEmpty(data.get("brand"));
        sql.append(" select * from ( SELECT e.*,c.plate_num,c.run_mile , c.car_age,c.series seriesName FROM (" +
                "select e.*,bc.o_name from t_crm_car_exsurance e left join ");
        sql.append(" t_bc_organ bc  ");
        sql.append(" on bc.id=e.company_id ");
        sql.append(" where e.company_id = ? ");
        params.add(companyId);
        // Constant.companyAndAreaAndBrand(uid,companyId,area,brand,sql,params,"bc");
        sql.append(" )e ");
        sql.append(",t_crm_car c  where c.vin  = e.vin ");

        //车型
        Object objSeries = data.get("series");
        if (objSeries != null) {
            ArrayList strSeries = (ArrayList) objSeries;
            StringBuffer tempBuf = new StringBuffer();
            if (strSeries.size() > 0) {
                sql.append(" and ( ");
                for (Object str : strSeries) {
                    tempBuf.append(" locate(? ,c.series) OR");
                    params.add((String) str);
                }
                sql.append(tempBuf.substring(0, tempBuf.length() - 2).toString());
                sql.append(" ) ");
            }
        }
        //车领计算
        //增加车领计算
        Object ageObj = data.get("carAge");
        if (null != ageObj) {
            List<String> ages = (List<String>) ageObj;
            if (ages.size() > 0) {
                StringBuffer tempAgeBuf = new StringBuffer();
                for (String age : ages) {
                    switch (age) {
                        case "9":
                            tempAgeBuf.append(" or  c.car_age >= ? ");
                            params.add(Integer.valueOf(age));
                            break;
                        default:
                            tempAgeBuf.append(" or ( c.car_age = ? ) ");
                            params.add(Integer.valueOf(age));
                            break;
                    }

                }
                if (tempAgeBuf.toString().length() > 0) {
                    sql.append(" AND ( 1>2 ");
                    //去除第一个 or
                    sql.append(tempAgeBuf);
                    sql.append(" )");
                }
            }
        }

        // 延保类型
        String strType = (String) data.get("type");
        if (!strType.isEmpty()) {
            sql.append(" and e.exsurance_company_id = ? ");
            params.add(strType);
        }

        // 合同时间范围
        //延保起始
        Map mapTime = (HashMap) data.get("time");
        if (mapTime.size() > 0) {
            String startTime = String.valueOf(mapTime.get("startTime"));
            if (startTime.length() > 0 && !"null".equals(startTime)) {
                Long startTimeLong = DateUtils.parseTime(startTime + " 00:00:00", "yyyy-MM-dd 00:00:00");
                sql.append(" and e.restart_insurance >= ?  ");
                params.add(startTimeLong);
            }

            String stopTime = String.valueOf(mapTime.get("stopTime"));
            if (stopTime.length() > 0 && !"null".equals(stopTime)) {
                Long stopTimeLong = DateUtils.parseTime(stopTime + " 24:00:00", "yyyy-MM-dd 24:00:00");
                sql.append(" and e.restart_insurance <= ?  ");
                params.add(stopTimeLong);
            }

        }

        //查询条件
        //筛选输入项
        Map mapSelect = (HashMap) data.get("select");
        if (!"".equals(StringUtil.formatEmpty(mapSelect.get("value")))) {
            switch ((String) mapSelect.get("key")) {
                //车牌号
                case "1": {
                    sql.append(" and c.plate_num like ? ");
                    params.add("%" + mapSelect.get("value") + "%");
                }
                break;
                //车架号
                case "2": {
                    sql.append(" and c.vin like ? ");
                    params.add("%" + mapSelect.get("value") + "%");
                }
                break;
                //联系人姓名
                case "3": {
                    sql.append(" and c.contact_name like ? ");
                    params.add("%" + mapSelect.get("value") + "%");
                }
                break;
                //联系人电话
                case "4": {
                    sql.append(" and c.contact_phone like ? ");
                    params.add("%" + mapSelect.get("value") + "%");
                }
                break;
            }
        }

        //延保状态
        String strStatus = (String) data.get("status");
        if (!strStatus.isEmpty()) {
            Calendar calendar = Calendar.getInstance();
            Long dateCurrent = new Date().getTime();


            switch (strStatus) {
                //一个月内到期
                case "1": {
                    sql.append(" and (e.mile_status < 2 and e.restop_insurance between ? and ? ) ");
                    calendar.setTime(new Date());
                    calendar.add(Calendar.MONTH, 1);
                    Long time1 = calendar.getTime().getTime();
                    params.add(dateCurrent);
                    params.add(time1);
                    //System.out.println(time1);
                }
                break;
                //两个月内到期
                case "2": {
                    sql.append(" and (e.mile_status < 2 and e.restop_insurance between ? and ? ) ");
                    calendar.setTime(new Date());
                    calendar.add(Calendar.MONTH, 2);
                    Long time2 = calendar.getTime().getTime();
                    params.add(dateCurrent);
                    params.add(time2);
                    //System.out.println(time2);
                }
                break;
                //三个月内到期
                case "3": {
                    sql.append(" and (e.mile_status < 2 and e.restop_insurance between ? and ? ) ");
                    calendar.setTime(new Date());
                    calendar.add(Calendar.MONTH, 3);
                    Long time3 = calendar.getTime().getTime();
                    params.add(dateCurrent);
                    params.add(time3);
                    //System.out.println(time2);
                    //System.out.println(time3);
                }
                break;
                //在质保--质保日期未过+延保日期未过+（结束里程-开始里程>100000）
                //行驶里程未超出 + 时间未超出
                case "4": {
                    sql.append(" and ( e.mile_status ='0' and   e.restart_insurance >= ? )");
                    params.add(dateCurrent);
                }
                break;
                //在延保
                // 时间进入 或里程时入
                case "5": {
                    sql.append(" and ( ( e.mile_status = '1' and e.restop_insurance >= ? ) or (e.mile_status='0' and e.restart_insurance <= ? and e.restop_insurance >= ? ) ) ");
                    params.add(dateCurrent);
                    params.add(dateCurrent);
                    params.add(dateCurrent);
                }
                break;
                //已过期
                case "6": {
                    //已出保
                    sql.append(" and (e.restop_insurance <= ? or e.mile_status = '2') ");
                    // System.out.println(dateCurrent);
                    params.add(dateCurrent);
                }
                break;
//                //在质保
//                case "7": {
//                    //车辆未出质保期
//                    sql.append(" and (c.guarantee_end_date > ? and e.mile_status = '0' )");
//                    System.out.println(dateCurrent);
//                    params.add(dateCurrent);
//                }
//                break;

            }
        }

        // 车辆公司
        sql.append(" and e.company_id = ? ");
        params.add(companyId);
//        Constant.VIN_TO_SQL(sql,uid,"c");


        /**2017年10月19日09:52:43 修改 延保管理权限放开，改为所有用户都可查看**/
      /*  if (companyId.equals(TokenUtil.getCompanyId(uid))) {
            confService.crmCarConfToSql(uid, sql, "c", companyId);
        }*/


//        // 车辆分配
//        // 查询其分配的车辆
//        Map info = refCar(uid);
//        //未分配车辆
//        if (null == info || info.size() == 0) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//
//        //车辆分配类型
//        String refType = String.valueOf(info.get("type"));
//        if (StringUtils.isEmpty(refType) || "null".equals(refType.toLowerCase())) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//        //车辆分配值，车属号 或车尾数，vin时 另行处理
//        String refValue = String.valueOf(info.get("value"));
//        refValue = refValue.replaceAll(",", "");
//        //根据类型取车辆
//
//        switch (refType) {
//            case Constant.CAR_WH:
//                sql.append(" AND  c.plate_num REGEXP ? ");
//                params.add("[" + refValue + "]$");
//                break;
//            case Constant.CAR_WS:
//                //先不写
//                sql.append(" AND c.plate_num REGEXP ? ");
//                params.add(".*[" + refValue + "][A-Za-z]*$");
//                //根据尾数查询
//                break;
//            case Constant.CAR_ALL:
//                //全部车辆
//                break;
//            default:
//                throw new Exception("车辆分配错误，请联系管理员！");
//        }
        sql.append(" order by c.plate_num desc ) temp3");
//        sql.append(" order by create_time DESC,restart_insurance desc ) temp3");
        return this.itCrmCarExsuranceDao.page(sql.toString(), params.toArray(), start, limit);

    }

    /**
     * @param start       当前页面
     * @param limit       页面大小
     * @param contactName 联系人名称
     * @return Map
     * @throws Exception
     * @desc
     * @author 徐钦勇
     */
    @Override
    public Map pageOwner(String uid, String start, String limit, String contactName) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select c.vin,c.contact_name,c.contact_phone,c.series,c.plate_num from T_CRM_CAR c where 1=1 ");
        String oid = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        if (!StringUtils.isEmpty(contactName)) {
            sql.append("and ( c.vin like ? or c.plate_num like ?)");
            params.add("%" + contactName + "%");
            params.add("%" + contactName + "%");
        }
        sql.append("and c.company_id = ? ");
        params.add(oid);
//        Constant.VIN_TO_SQL(sql,uid,"c");
        confService.crmCarConfToSql(uid, sql, "c", oid);
//        // 车辆分配
//        // 查询其分配的车辆
//        Map info = refCar(uid);
//        //未分配车辆
//        if (null == info || info.size() == 0) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//
//        //车辆分配类型
//        String refType = String.valueOf(info.get("type"));
//        if (StringUtils.isEmpty(refType) || "null".equals(refType.toLowerCase())) {
//            throw new Exception("该用户未分配车辆，请联系管理员！");
//        }
//        //车辆分配值，车属号 或车尾数，vin时 另行处理
//        String refValue = String.valueOf(info.get("value"));
//        refValue = refValue.replaceAll(",", "");
//        //根据类型取车辆
//
//        switch (refType) {
//            case Constant.CAR_WH:
//                sql.append(" AND  c.plate_num REGEXP ? ");
//                params.add("[" + refValue + "]$");
//                break;
//            case Constant.CAR_WS:
//                //先不写
//                sql.append(" AND c.plate_num REGEXP ? ");
//                params.add(".*[" + refValue + "][A-Za-z]*$");
//                //根据尾数查询
//                break;
//            case Constant.CAR_ALL:
//                //全部车辆
//                break;
//            default:
//                throw new Exception("车辆分配错误，请联系管理员！");
//        }
        return this.itCrmCarExsuranceDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * @param data TCrmCarExsurance实体
     * @return Map
     * @throws Exception
     * @desc
     * @author 徐钦勇
     */
    @Override
    public TCrmCarExsurance saveOrUpdate(TCrmCarExsurance data) throws Exception {

        List params = new ArrayList();
        String sql = "select * from T_CRM_CAR_EXSURANCE where  vin = ? ";
        params.add(data.getVin());

        if (data.getId() != null) {
            sql += " and id != ? ";
            params.add(data.getId());
            data.setMileStatus("0");
        }
        sql += " ORDER by restop_insurance desc limit 1 ";
        Map map = this.itCrmCarExsuranceDao.info(sql, params.toArray());

        //存在历史记录，判断合同开始-合同结束
        //存在历史记录，去执行判断
        if (null != map && map.size() > 0) {
            if (!String.valueOf(map.get("restopInsurance")).equals("null") && !StringUtils.isEmpty(String.valueOf(map.get("stopLegend")))) {
                System.out.println(String.valueOf(map.get("restopInsurance")));
                System.out.println(String.valueOf(map.get("stopLegend")));

                Integer stopLegend = Double.valueOf(String.valueOf(map.get("stopLegend"))).intValue();
                Long restopInsurance = Double.valueOf(String.valueOf(map.get("restopInsurance"))).longValue();

                if (Integer.valueOf(data.getStartLegend()) < stopLegend || Long.valueOf(data.getRestartInsurance()) < restopInsurance || Integer.valueOf(data.getStopLegend()) < Integer.valueOf(data.getStartLegend()) || data.getRestopInsurance() < data.getRestartInsurance()) {
                    throw new Exception("已存在相同里程区间或合同起止区间的记录，请确认后再提交！");
                }
            } else if (!String.valueOf(map.get("restopInsurance")).equals("null") && StringUtils.isEmpty(String.valueOf(map.get("stopLegend")))) {


                //  Integer stopLegend = Integer.valueOf(String.valueOf(map.get("stopLegend")));
                Long restopInsurance = Double.valueOf(String.valueOf(map.get("restopInsurance"))).longValue();

                if (Long.valueOf(data.getRestartInsurance()) < restopInsurance || Integer.valueOf(data.getStopLegend()) < Integer.valueOf(data.getStartLegend()) || data.getRestopInsurance() < data.getRestartInsurance()) {
                    throw new Exception("已存在相同里程区间或合同起止区间的记录，请确认后再提交！");
                }

            } else if (String.valueOf(map.get("restopInsurance")).equals("null") && !StringUtils.isEmpty(String.valueOf(map.get("stopLegend")))) {

                Integer stopLegend = Double.valueOf(String.valueOf(map.get("stopLegend"))).intValue();
                // Long restopInsurance = Long.valueOf(String.valueOf(map.get("restopInsurance")));

                if (Integer.valueOf(data.getStartLegend()) < stopLegend || Integer.valueOf(data.getStopLegend()) < Integer.valueOf(data.getStartLegend()) || data.getRestopInsurance() < data.getRestartInsurance()) {
                    throw new Exception("已存在相同里程区间或合同起止区间的记录，请确认后再提交！");
                }
            }

        }
        return (TCrmCarExsurance) this.itCrmCarExsuranceDao.saveOrUpdate(data);
    }

    /**
     * @param start
     * @param limit
     * @return Map
     * @throws Exception
     * @desc
     * @author 徐钦勇
     */
    @Override
    public Map impPage(String start, String limit, String oid) throws Exception {
        String sqlBuffer = "select * from " + tabName + " where 1=1 ";
        List<String> paramList = new ArrayList<String>();
        if (!StringUtils.isEmpty(oid)) {
            sqlBuffer += " and company_id = ? ";
            paramList.add(oid);
        }
        return this.iImpJdbcDao.queryForPageMap(start, limit, sqlBuffer, paramList.toArray());

    }

    /**
     * 根据 实体 ID，删除记录
     *
     * @param objId
     * @return
     */
    @Override
    public boolean clearById(String objId) throws Exception {
        String hql = "delete from TCrmCarExsurance where id = :id";
        Map params = new HashMap();
        params.put("id", objId);
        this.iImpHibernateDao.executeHqlWithParams(hql, params);
        return true;
    }

    /**
     * @param id 核销 id
     * @return Map
     * @throws Exception
     * @desc 延保导入确认
     * @author 徐钦勇
     */
    @Override
    public void impConfirm(String id, String uid) throws Exception {
        String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and restart_insurance = ? and contract_num = ? and company_id = ? limit 1";
        Map existData;
        List<Object> idList = new ArrayList();
        Object obj = this.iImpHibernateDao.findEntity(TCrmCarExsurance.class, id);
        if (obj == null) {
            throw new Exception("无效的数据！");
        }
        TCrmCarExsurance ex = (TCrmCarExsurance) obj;
        existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getRestartInsurance(), ex.getContractNum(), ex.getCompanyId());
        if (existData.size() == 0) {
            ex.setId(null);
            ex.setCreateTime(new Date().getTime());
            ex.setUpdateTime(new Date().getTime());
            ex.setConfirmer(uid);
            ex.setConfirmDate(new Date().getTime());
            ex.setMileStatus("0");
        } else {
            //已有数据
            ex.setId(existData.get("id").toString());
            ex.setUpdateTime(new Date().getTime());
            ex.setConfirmer(uid);
            ex.setConfirmDate(new Date().getTime());
        }

        idList.add(id);
        this.itCrmCarExsuranceDao.saveOrUpdate(ex);
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
        idList.clear();
    }

    /**
     * @param data 批量数据
     * @return Map
     * @throws Exception
     * @desc 延保批量确认
     * @author 徐钦勇
     */
    @Override
    public void multiImpConfirm(List<Map> data, String uid) throws Exception {
        TCrmCarExsurance ex;
        Map existData;
        List<Object> idList = new ArrayList();
        for (Map map : data) {
            String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and restart_insurance = ? and contract_num = ? and company_id = ? limit 1 ";
            String tempId = String.valueOf(map.get("id"));
            Object obj = iImpHibernateDao.findEntity(TCrmCarExsurance.class, tempId);
            if (obj == null) {
                throw new Exception("无对应数据！");
            }
            ex = (TCrmCarExsurance) obj;
            existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getRestartInsurance(), ex.getContractNum(), ex.getCompanyId());
            //源数据主键
            idList.add(tempId);
            if (existData.size() == 0) {
                //新数据
                ex.setId(null);
                ex.setCreateTime(new Date().getTime());
                ex.setUpdateTime(new Date().getTime());
                ex.setConfirmer(uid);
                ex.setConfirmDate(new Date().getTime());
                ex.setMileStatus("0");
            } else {
                //已有数据
                ex.setId(existData.get("id").toString());
                ex.setUpdateTime(new Date().getTime());
                ex.setConfirmer(uid);
                ex.setConfirmDate(new Date().getTime());
            }
            this.itCrmCarExsuranceDao.saveOrUpdate(ex);
        }
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
        idList.clear();
    }

    /**
     * @return Map
     * @throws Exception
     * @desc 延保全部确认
     * @author 徐钦勇
     */
    @Override
    public void impConfirmAll(String uid) throws Exception {
        //获取公司 ID
        String companyId = TokenUtil.getCompanyId(uid);
        //编写查询源数据 HQL
        String hql = "from TCrmCarExsurance where companyId = :companyId";
        //设置参数
        Map<String, Object> params = new HashMap();
        params.put("companyId", companyId);
        //查询公司下的全部延保
        List<TCrmCarExsurance> tCrmCarExsurance = iImpHibernateDao.findEntityListByHqlWithParams(hql, params);
        if (tCrmCarExsurance == null) {
            throw new Exception("无效的数据！");
        }
        //每50条保存一次
        List<Object> idList = new ArrayList<>();
        Map existData;
        String tempId;
        String EXIST_DATA_SQL = "select * from " + tabName + " where vin = ? and restart_insurance = ? and contract_num = ? and company_id = ? limit 1";
        for (TCrmCarExsurance ex : tCrmCarExsurance) {
            existData = this.jdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, ex.getVin(), ex.getRestartInsurance(), ex.getContractNum(), ex.getCompanyId());
            //源数据主键
            tempId = ex.getId();
            idList.add(tempId);
            if (existData.size() == 0) {
                ex.setId(null);
                ex.setConfirmDate(new Date().getTime());
                ex.setConfirmer(uid);
                ex.setCreateTime(new Date().getTime());
                ex.setUpdateTime(new Date().getTime());
                ex.setMileStatus("0");
            } else {
                //已有数据
                ex.setId(existData.get("id").toString());
                ex.setUpdateTime(new Date().getTime());
                ex.setConfirmer(uid);
                ex.setConfirmDate(new Date().getTime());
            }
            //保存或更新
            this.iHibernateDao.saveOrUpdateEntity(ex);
            if (idList.size() == 500) {
                this.iImpJdbcDao.batchDel(tabName, "id", idList);
                idList.clear();
            }
        }
        //处理剩余数据
        if (idList.size() > 0) {
            this.iImpJdbcDao.batchDel(tabName, "id", idList);
            idList.clear();
        }
        //同步车型车系
        this.iCarBaseCountService.updateExCarSeriesQuartz();
        //同步车辆id
        this.itCrmCarWorkorderTaskService.updWorkOrderCaridInfoQuartz();
        //结束里程同步、
        this.iCarBaseCountService.updateExCarMileQuartz();
    }


    /**
     * @return
     * @throws Exception
     * @desc 删除全部待导入数据
     * @author 术洪超
     */
    @Override
    public void impDelAll(String uid) throws Exception {

        Map map = new HashMap();
        String companyId = TokenUtil.getCompanyId(uid);
        String hql = " delete from TCrmCarExsurance where companyId =:companyId";
        map.put("companyId", companyId);
        //System.out.println(companyId);

        this.iImpHibernateDao.executeHqlWithParams(hql, map);
    }

    @Override
    public void impDels(List<Map<Object, String>> data, String uid) throws Exception {


        List<Object> idList = new ArrayList();
        for (Map map : data) {
            idList.add(map.get("id"));
        }

        this.iImpJdbcDao.batchDel(tabName, "id", idList);
    }


    private Map<String, Object> refCar(String uid) throws Exception {
        String sql = "select  * from t_crm_car_ref where u_id = ? and status = '1' ";
        Map info = this.itCrmCarExsuranceDao.info(sql, uid);
        return info;
    }
}

